package com.biqee.service.user.impl;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.biqee.model.db.BqUser;
import com.biqee.model.db.BqUserLoginName;
import com.biqee.service.db.BqUserLoginNameService;
import com.biqee.service.db.BqUserService;
import com.biqee.service.framework.impl.BaseTransactionSupportServiceImpl;
import com.biqee.service.user.RegisterService;
import com.biqee.util.PasswordUtil;

public class RegisterServiceImpl extends BaseTransactionSupportServiceImpl implements RegisterService {

	@Override
	public boolean registerLoginName(String loginName) {
		loginName = loginName.toLowerCase();
		final String destLoginName = loginName;
		
		@SuppressWarnings({ "rawtypes", "unchecked" })
		boolean result = getTransactionTemplate().execute(new TransactionCallback() {
			public Object doInTransaction(TransactionStatus status) {
				BqUserLoginName bqUserLoginName = bqUserLoginNameService.readByLoginName(destLoginName);
				if(bqUserLoginName != null) {
					return false;
				} else {
					bqUserLoginName = new BqUserLoginName();
					bqUserLoginName.setLoginName(destLoginName);
					bqUserLoginNameService.create(bqUserLoginName);
					return true;
				}
			}
		});
		
		return result;
	}

	@Override
	public BqUser createUserForTrustLogin() {
		BqUser bqUser = new BqUser();
		String loginName = null;
		while(loginName == null) {
			loginName = PasswordUtil.genRandomString(PasswordUtil.DEFAULT_LEN);
			loginName = loginName.toLowerCase();
			boolean registerResult = registerLoginName(loginName);
			if(!registerResult) {
				loginName = null;				
			}
		}
		
		bqUser.setLoginName(loginName);		
		String password = PasswordUtil.genRandomString(PasswordUtil.DEFAULT_LEN);
		bqUser.setPassword(password);
		
		Long id = bqUserService.create(bqUser);
		bqUser.setId(id);
		return bqUser;
	}
	
	
	private BqUserService bqUserService;

	public void setBqUserService(BqUserService bqUserService) {
		this.bqUserService = bqUserService;
	}

	private BqUserLoginNameService bqUserLoginNameService;

	public void setBqUserLoginNameService(
			BqUserLoginNameService bqUserLoginNameService) {
		this.bqUserLoginNameService = bqUserLoginNameService;
	}
	
	
}
